import { defineStore } from "pinia";
import { getUserInfo, getMenuList } from "@/network/api/api-base";
import { removeToken } from "@/utils/auth";
import { useMenuStore } from "./menu";

export const useUserStore = defineStore("user", {
    state: () => ({
        userInfo: {},
        isSuper: false,
    }),

    actions: {
        // 获取用户信息
        async _getUserInfo() {
            try {
                const menuStore = useMenuStore();
                const [userRes, menuRes] = await Promise.all([
                    getUserInfo(),
                    getMenuList(),
                ]);

                if (menuRes.data?.menu?.length) {
                    menuRes.data.menu.forEach((item) => this._formatMenu(item));
                    menuStore.saveMenu(menuRes.data.menu);
                }

                this.userInfo = {
                    name: userRes.data.name,
                    id: userRes.data.id,
                };
            } catch (error) {
                throw error;
            }
        },

        // 退出登录
        async resetToken() {
            const menuStore = useMenuStore();
            menuStore.saveMenu([]);
            this.userInfo = {};
            removeToken();
        },

        // 私有方法(通过下划线前缀表示)
        _formatMenu(menu) {
            menu.name = menu.path;
            menu.meta = { title: menu.menuName };
            menu.path = menu.url;

            menu.component =
                menu.url.split("/").length === 2
                ? "Layout"
                : `${menu.url.split("/")[1]}/${this._toHump(menu.url.split("/")[2])}`;

            menu.children?.forEach((item) => this._formatMenu(item));
        },

        _toHump(name) {
            return name.split("-").map((word) => word.replace(/^\w/, (l) => l.toUpperCase())).join("");
        },
    },
});
